<template>
  <div class="about">
    <h2>App2 - About Page</h2>
    
    <div class="info-section">
      <h3>从主应用或其他子应用同步的用户信息：</h3>
      <p>用户名：{{ userInfo?.name }}</p>
      <p>年龄：{{ userInfo?.age }}</p>
      <p v-if="syncMessage" class="sync-message">{{ syncMessage }}</p>
    </div>
    
    <div class="communication-demo">
      <h3>应用间通信演示：</h3>
      <p>此页面展示了微前端架构下的数据共享能力</p>
      <div class="demo-steps">
        <h4>演示步骤：</h4>
        <ol>
          <li>在主应用或App1中修改用户信息</li>
          <li>观察此页面上的数据是否自动更新</li>
          <li>切换不同的子应用，验证数据一致性</li>
        </ol>
      </div>
    </div>
    
    <div class="tech-info">
      <h3>技术栈信息：</h3>
      <ul>
        <li>前端框架：Vue 3</li>
        <li>构建工具：Vite</li>
        <li>微前端框架：qiankun</li>
        <li>状态管理：Pinia</li>
        <li>路由管理：Vue Router</li>
      </ul>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 用户信息
const userInfo = ref<any>(null)
const syncMessage = ref('')
let checkStateInterval: ReturnType<typeof setInterval> | null = null
let lastUserInfoHash = ''

// 获取全局状态
const getGlobalState = () => {
  const globalState = (window as any).__MICRO_APP_ENVIRONMENT__?.globalState
  if (globalState && globalState.userInfo) {
    const currentUserInfoHash = JSON.stringify(globalState.userInfo)
    // 只有当用户信息发生变化时才更新
    if (currentUserInfoHash !== lastUserInfoHash) {
      lastUserInfoHash = currentUserInfoHash
      userInfo.value = { ...globalState.userInfo }
      showSyncMessage()
    }
  }
}

// 显示同步消息
const showSyncMessage = () => {
  const now = new Date()
  syncMessage.value = `数据已从其他应用同步 (${now.toLocaleTimeString()})`
  
  // 3秒后清除消息
  setTimeout(() => {
    syncMessage.value = ''
  }, 3000)
}

onMounted(() => {
  // 获取初始状态
  getGlobalState()
  
  // 设置定时器检查状态变化
  checkStateInterval = setInterval(() => {
    getGlobalState()
  }, 500)
})

onUnmounted(() => {
  // 清理定时器
  if (checkStateInterval) {
    clearInterval(checkStateInterval)
  }
})
</script>

<style scoped>
.about {
  padding: 20px;
}

h2 {
  color: #2196f3;
  margin-bottom: 20px;
}

.info-section,
.communication-demo,
.tech-info {
  background-color: #f8f8f8;
  padding: 15px;
  margin-bottom: 20px;
  border-radius: 8px;
}

h3 {
  margin-top: 0;
  color: #333;
}

h4 {
  margin-top: 10px;
  color: #555;
}

.sync-message {
  background-color: #fff3cd;
  color: #856404;
  padding: 10px;
  border-radius: 4px;
  border-left: 4px solid #ffc107;
}

ol,
ul {
  margin-top: 10px;
  padding-left: 20px;
}

li {
  margin-bottom: 5px;
}

.demo-steps {
  background-color: #e3f2fd;
  padding: 10px;
  border-radius: 4px;
}

.tech-info ul li {
  display: inline-block;
  margin-right: 10px;
  padding: 5px 10px;
  background-color: #e3f2fd;
  border-radius: 4px;
}
</style>